package com.thti.mecool.client.base;

import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Message;

import com.thti.mecool.client.command.ICommand;
import com.thti.mecool.client.command.ManageCommand;
import com.thti.mecool.client.model.biz.TaskManageBizImpl;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.model.po.TaskStep;
import com.thti.mecool.client.protocol.plan.PlanStep;
import com.thti.mecool.client.service.Protocol;
import com.thti.mecool.client.util.NetTool;
import com.thti.mecool.client.util.Util;

public class ImageUpload {
	Activity myActivity;
	TaskManageBizImpl bizImpl;
	String planId;
	public ImageUpload(Activity activity) {
		myActivity = activity;
	}

	@SuppressWarnings("unchecked")
	public void uploadImage(int flag) {
		 bizImpl = new TaskManageBizImpl(myActivity);
		List<TaskManage> list =(flag==0)?bizImpl.findByImage():bizImpl.findAll();
		     
		if (null != list && list.size() > 0) {
			try {
				InputStream in =null;
				if(flag==0){
				 in =NetTool.upload_image(list,BaseActivity.getCurrentUser().getLoginName());
				}else{
					String json=uploadPlan();
					System.out.println("image json:  "+json);
					if(json==null){
						return;
					}
					in=NetTool.POSTJson(Protocol.getURL
							+ Protocol.getUploadPlan.replaceAll("_", "/")+"?userLoginName="+BaseActivity.getCurrentUser().getLoginName()+"&plan_id="+planId, json);
				Util.print(Protocol.getURL
							+ Protocol.getUploadPlan.replaceAll("_", "/")+"?userLoginName="+BaseActivity.getCurrentUser().getLoginName()+"&plan_id="+planId);
				Util.print("json：  "+json);
				}
				if (null != in) {
					byte[] bytes = NetTool.read(in);
					JSONObject jsons = new JSONObject(new String(bytes));
					String protocolID = jsons.get("command").toString();
					String id = jsons.get("result").toString();
					if (Integer.parseInt(id) == 0) {
						Util.print("服务器返回错误");
						Message msg = new Message();
						BaseActivity.serverErrorHandler.sendMessage(msg);
						return;
					}
					if (!ManageCommand.commads.containsKey(protocolID)) {
						Util.print("Command [" + protocolID + "] Not Found ...");
						return;
					} else {
						ICommand command = ManageCommand.commads
								.get(protocolID);
						Util.print("protocolID:  "+protocolID);
						Util.print(jsons.get("body").toString());
						Util.print(command.getCommandClass());
						ObjectMapper mapper = new ObjectMapper();
						Object obj = mapper.readValue(jsons.get("body")
								.toString(), command.getCommandClass());
						command.doCommand(obj);
					}
				} else {
					Message msg = new Message();
					BaseActivity.serverErrorHandler.sendMessage(msg);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		
		}
	}
	
	public String uploadPlan(){
		bizImpl = new TaskManageBizImpl(myActivity);
		List<TaskManage> list = bizImpl.findAll();
		String dataJSON=null;
		if (null != list && list.size() > 0) {
			if(list.size()<3){
				return null;
			}
			ObjectMapper mapper = new ObjectMapper();
			List<PlanStep> listStep=new  ArrayList<PlanStep>();
			planId=list.get(0).getPlanId();
			for (int i = 0; i < list.size(); i++) {
				PlanStep planStep=new PlanStep();
				planStep.setPlanProjectId(Long.parseLong(list.get(i).getProjectId()));
				planStep.setPlanJobId(Long.parseLong(list.get(i).getTaskId()));
				planStep.setStepId(Long.parseLong(list.get(i).getStepId()));
				planStep.setData(list.get(i).getData());
				planStep.setFinishedAt(new Date());
				planStep.setLatitude(list.get(i).getLatitude());
				planStep.setLongitude(list.get(i).getLongitude());
				listStep.add(planStep);
			}
			Writer strWriter = new StringWriter();
			try {
				mapper.writeValue(strWriter, listStep);
			}catch (Exception e) {
				// TODO: handle exception
			}
			 dataJSON = strWriter.toString();
		}
		
		return dataJSON;
	}
	
	
}
